﻿using QD.SQLHelper;
using QD.Tools;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace QD.DbManager
{
    public partial class ViewManager : DbBasic
    {
        EFDbContext dbContext;
        LogonConfig logonConfig;

        public ViewManager(LogonConfig logonConfig, string curDbName)
        {
            InitializeComponent();

            this.logonConfig = logonConfig;
            string dbConnStr = logonConfig.GetConnectionStrings("master");
            EFDbContext masterContext = new EFDbContext(dbConnStr);
            IList<SysDatabases> databases = masterContext.Databases();
            foreach (SysDatabases db in databases)
            {
                this.comDbSource.Items.Add(db.name);
            }

            this.comDbSource.Text = curDbName;
            dbContext = new EFDbContext(logonConfig.GetConnectionStrings(curDbName));

            this.grid.RowTemplate.ContextMenuStrip = this.contextMenuStrip1;
            DataGridViewHelper.InitGrid(this.grid);

            this.treeView1.ContextMenuStrip = this.contextMenuStrip2;
            this.StartPosition = FormStartPosition.CenterScreen;
        }

        private void ViewManager_Load(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            Thread t = new Thread(new ThreadStart(Grid_DataBind));
            t.IsBackground = true;
            t.Start();
        }

        private void Grid_DataBind()
        {
            this.Invoke((EventHandler)(delegate
            {
                string viewName = this.txtViewName.Text.Trim();
                string condition = string.Empty;
                if (viewName.Length > 0)
                {
                    if (!QD.Tools.ValueTypeHelper.IsInt(viewName))
                    {
                        condition = string.Format("name like '%{0}%'", viewName);
                    }
                    else
                    {
                        condition = string.Format("object_id ={0}", viewName);
                    }
                }
                IList<SysViews> views = dbContext.Views(condition);
                this.grid.DataSource = views;
            }));
        }

        private void 复制ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            TreeViewHelper.CopyFirstSelectedNodeText(this.treeView1);
        }

        private void 复制ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.grid.CopyFirstSelectedCellValue();
        }

        private void 复制选中单元格ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.grid.CopySelectedCellsValue();
        }

        private void 创建新增脚本ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedCellCollection cells = this.grid.SelectedCells;
            if (cells.Count > 0)
            {
                DataGridViewCell cell = cells[0];

                string viewName = GetSelectCellViewName(cell);

                string text = dbContext.GetText(viewName);

                Form frm = new SQLContainer(DbConfig.Instance.LogonConfig, DbConfig.Instance.DbConfigName, text);
                frm.ShowDialog();
            }
        }

        private void 创建选中行新增脚本ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedCellCollection cells = this.grid.SelectedCells;
            if (cells.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (DataGridViewCell cell in cells)
                {
                    string viewName = GetSelectCellViewName(cell);

                    string text = dbContext.GetText(viewName);
                    sb.Append(text);
                }

                Form frm = new SQLContainer(DbConfig.Instance.LogonConfig, DbConfig.Instance.DbConfigName, sb.ToString());
                frm.ShowDialog();
            }
        }

        private void comDbSource_SelectedIndexChanged(object sender, EventArgs e)
        {
            dbContext = new EFDbContext(logonConfig.GetConnectionStrings(this.comDbSource.Text));
        }

        private void grid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                string viewName = this.grid.Rows[e.RowIndex].Cells["name"].Value.ToString();
                TableManager.BindTreeView(dbContext, this.treeView1, viewName);
            }
        }

        private void 显示表结构ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedCellCollection cells = this.grid.SelectedCells;
            if (cells.Count > 0 && grid.Columns[cells[0].ColumnIndex].Name == "name")
            {
                string viewName = cells[0].Value.ToString();
                TableManager.BindTreeView(dbContext, this.treeView1, viewName);
            }
        }

        private void 查看数据前100行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedCellCollection cells = this.grid.SelectedCells;
            if (cells.Count > 0)
            {
                DataGridViewCell cell = cells[0];
                string viewName = GetSelectCellViewName(cell);

                string sql = "select top 100 * from " + viewName;
                Form frm = new SQLContainer(DbConfig.Instance.LogonConfig, this.comDbSource.SelectedItem.ToString(), sql);
                frm.ShowDialog();
            }
        }

        private string GetSelectCellViewName(DataGridViewCell cell)
        {
            int rowIndex = cell.RowIndex;
            DataGridViewRow dr = this.grid.Rows[rowIndex];
            string viewName = dr.GetCellValueToString("name"); ;
            return viewName;
        }

        [DllImport("User32.DLL")]
        public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, string lParam);
        [DllImport("User32.DLL")]
        public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
        public const uint WM_SETTEXT = 0x000C;

        private void 刷新视图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StringBuilder failText = new StringBuilder();
            DataGridViewSelectedCellCollection cells = this.grid.SelectedCells;
            if (cells.Count > 0)
            {
                DataGridViewCell cell = cells[0];
                string viewName = GetSelectCellViewName(cell);
                string text = dbContext.RefreshView(viewName);

                this.toolStripStatusLabel1.Text = text;
                if (text.Contains("验证失败"))
                {
                    failText.AppendLine(text);
                }
            }

            if (failText.ToString().Length > 0)
            {
                GeneralTools.OpenNotepad(failText.ToString());
            }
        }

        private void 刷新选中行视图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StringBuilder failText = new StringBuilder();
            DataGridViewSelectedCellCollection cells = this.grid.SelectedCells;
            if (cells.Count > 0)
            {
                foreach (DataGridViewCell cell in cells)
                {
                    string viewName = GetSelectCellViewName(cell);
                    string text = dbContext.RefreshView(viewName);

                    this.toolStripStatusLabel1.Text = text;
                    this.statusStrip1.Update();
                    if (text.Contains("验证失败"))
                    {
                        failText.AppendLine(text);
                    }
                }
            }

            if (failText.ToString().Length > 0)
            {
                GeneralTools.OpenNotepad(failText.ToString());
            }
        }

        private void 刷新所视图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StringBuilder failText = new StringBuilder();
            IList<DataGridViewRow> rows = this.grid.GetAllRows();
            if (rows.Count > 0)
            {
                foreach (DataGridViewRow row in rows)
                {
                    string viewName = row.GetCellValueToString("name"); ;
                    string text = dbContext.RefreshView(viewName);

                    this.toolStripStatusLabel1.Text = text;
                    this.statusStrip1.Update();
                    if (text.Contains("验证失败"))
                    {
                        failText.AppendLine(text);
                    }
                }
            }

            if (failText.ToString().Length > 0)
            {
                GeneralTools.OpenNotepad(failText.ToString());
            }
        }

        private void txtViewName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.button2_Click(sender, e);
            }
        }
    }
}
